#!/bin/bash
set -o pipefail
set -o errexit

APP_NAME="third-party.jar"
APP_PATH="/data/${APP_NAME}"
APP_PORT=8000
APP_TAG="dev_id_20210709_02"

MAX_DIRECT_SIZE=256 	#heapoff size
META_SIZE=128	 		#metaspace size
MAX_META_SIZE=256 		#max metaspace size

if [[ -z ${MEMORY} ]];then
    echo "Env MEMORY Not Found"
    exit 1
fi

MEMORY_SIZE=$((${MEMORY} / 1024 / 1024))

if [[ ${MEMORY_SIZE} <1600 ]];then
	MAX_DIRECT_SIZE=128
fi

HEAP_SIZE=$((${MEMORY_SIZE} - ${MAX_DIRECT_SIZE} - ${META_SIZE}))
NEW_GEN_SIZE=$((${HEAP_SIZE}  * 3 / 4))

PH_TIMEZONE="Asia/Manila"
ID_TIMEZONE="Asia/Jakarta"
VN_TIMEZONE="Asia/Ho_Chi_Minh"


if [[ -z ${APP_NAME} ]];then
    echo "Please enter a valid application name"
    exit 1
fi

if [[ -z ${APP_ENV} ]];then
    echo "Please enter a valid APP_ENV"
    exit 1
fi

if [[ -z ${REGION_NAME} ]]; then
    TIMEZONE=${PH_TIMEZONE}
elif [[ ${REGION_NAME} == "finizi" ]]; then
    TIMEZONE=${VN_TIMEZONE}
elif [[ ${REGION_NAME} == "cashalo" ]]; then
    TIMEZONE=${PH_TIMEZONE}
elif [[ ${REGION_NAME} == "finmas" ]]; then
    TIMEZONE=${ID_TIMEZONE}
else
	echo $TIMEZONE
fi

if [[ -z ${SW_BUFFER_SIZE} ]];then 
	buffer_size=1000
else
	buffer_size=${SW_BUFFER_SIZE}
fi

if [[ -z ${SW_LOG_LEVEL} ]];then 
	log_level=off
else
	log_level=${SW_LOG_LEVEL}
fi

if [[ -n ${JVMOPTS} ]];then
	JVM_OPTS=${JVMOPTS}
else
	JVM_OPTS="-Xms${HEAP_SIZE}m -Xmx${HEAP_SIZE}m -XX:NewSize=${NEW_GEN_SIZE}m -XX:MaxNewSize=${NEW_GEN_SIZE}m -XX:MetaspaceSize=${META_SIZE}m -XX:MaxMetaspaceSize=${MAX_META_SIZE}m -XX:MaxDirectMemorySize=${MAX_DIRECT_SIZE}m"
fi

if [[ -z ${GCOPTS} ]];then
	GC_OPTS="-Djava.util.Arrays.useLegacyMergeSort=true -XX:ActiveProcessorCount=2 -XX:+UseParNewGC -XX:PretenureSizeThreshold=1M -XX:+CMSClassUnloadingEnabled  -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:LargePageSizeInBytes=128m -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=80"
else
	GC_OPTS=${GCOPTS}
fi

JAVA_OPTS="-server ${JVM_OPTS} ${GC_OPTS}"

SW_OPTS="-javaagent:/data/agent/skywalking-agent.jar -DSW_AGENT_NAME=${REGION_NAME}-${RUN_ENV}-third-party -DSW_AGENT_NAMESPACE=${namespace} -DSW_AGENT_COLLECTOR_BACKEND_SERVICES=apm.oriente.internal:11800,apm2.oriente.internal:11800 -DSW_LOGGING_LEVEL=${log_level} -Dplugin.springmvc.use_qualified_name_as_endpoint_name=true -Ddictionary.endpoint_name_buffer_size=${buffer_size}"


UNIT_OPTS="-Deureka.instance.metadata-map.tag=${APP_TAG} -Deureka.instance.metadata-map.unit=${UNIT}"

if [[ -z ${SKYWALKING} ]];then
	APM_OPTS=""
else
	APM_OPTS=$SW_OPTS
fi

if [[ ${APP_ENV} == "prod" ]]; then 
 	APM_OPTS=$SW_OPTS
fi

JAVA_RUN="java ${JAVA_OPTS} ${APM_OPTS} ${UNIT_OPTS} -jar -Dspring.profiles.active=${APP_ENV} ${APP_PATH} --server.port=${APP_PORT}"

ln -sf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime

exec $JAVA_RUN